package com.heima.search.config;

import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AppThreadUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 自定义的拦截器
 */
public class WmTokenInterceptor implements HandlerInterceptor {

    /**
     * 方法之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        //判断是否存在
        Optional<String> optional = Optional.ofNullable(token);
        if (optional.isPresent()) {
            //2.解析token，获取用户id
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Integer userId = (Integer) claimsBody.get("id");
            //3.存入threadLocal中
            ApUser apUser = new ApUser();
            apUser.setId(userId);
            AppThreadUtil.setUser(apUser);

        }
        return true;
    }

    /**
     * 方法之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //    从threadLocal中申请清理用户信息
        AppThreadUtil.clear();
    }
}
